package com.lu.manage.modular.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.manage.core.common.constant.SystemConstant;
import com.lu.manage.core.common.global.SystemCache;
import com.lu.manage.core.common.node.TreeNodes;
import com.lu.manage.core.common.page.LayuiPageFactory;
import com.lu.manage.core.shiro.ShiroKit;
import com.lu.manage.core.shiro.ShiroUser;
import com.lu.manage.core.shiro.service.UserAuthService;
import com.lu.manage.core.utils.ToolUtil;
import com.lu.manage.modular.system.mapper.UserMapper;
import com.lu.manage.modular.system.model.User;
import com.lu.manage.modular.system.service.DeptService;
import com.lu.manage.modular.system.service.MenuService;
import com.lu.manage.modular.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program LuBoot
 * @description:
 * @author: zhanglu
 * @create: 2019-10-08 10:30:00
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserAuthService userAuthService;

    @Autowired
    private DeptService deptService;

    @Override
    public List<TreeNodes> getUserMenuNodes(List<String> roleList) {
        if(ToolUtil.isEmpty(roleList)){
            return new ArrayList<>();
        }else {
            List<TreeNodes> menus = menuService.getMenusByRolesIds(roleList);
            List<TreeNodes> menuNodes = TreeNodes.buildTitle(menus);
            return menuNodes;

        }
    }

    @Override
    public void refreshCurrentUser() throws Exception {
        ShiroUser user = ShiroKit.getUserNotNull();
        String id = user.getId();
        User currentUser = this.getById(id);
        ShiroUser shiroUser = userAuthService.shiroUser(currentUser);
        ShiroUser lastUser = ShiroKit.getUser();
        BeanUtil.copyProperties(shiroUser, lastUser);
    }

    @Override
    public User add(User user) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", user.getAccount());
        // 判断账号是否重复
        Integer count = this.baseMapper.selectCount(queryWrapper);
        if (count != 0) {
            throw new Exception("该用户已经注册");
        }

        // 完善账号信息
        String salt = ShiroKit.getRandomSalt(5);
        String password = ShiroKit.md5(user.getPassword(), salt);

        user.setSalt(salt);
        user.setPassword(password);

        this.save(user);
        return user;
    }

    @Override
    public void update(User user) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", user.getAccount());
        queryWrapper.ne("id", user.getId());
        // 判断账号是否重复
        Integer count = this.baseMapper.selectCount(queryWrapper);
        if (count >= 1) {
            throw new Exception("该账号已经使用");
        }
        this.baseMapper.updateById(user);
    }

    @Override
    public void delete(String userId) throws Exception {
        this.baseMapper.deleteById(userId);
    }

    @Override
    public Object listPage(Map<String, Object> map) {

        QueryWrapper queryWrapper = LayuiPageFactory.deptScope(deptService, map);

        Page page = LayuiPageFactory.defaultPage(map);

        map.forEach((k, v) -> {
            if(k.equals(SystemConstant.SEARCH_WORDS)){
                queryWrapper.like("account", v);
                queryWrapper.like("name", v);
                queryWrapper.like("phone", v);
            }else {
                queryWrapper.eq(k, v);
            }
        });
        IPage<User> iPage = this.baseMapper.selectPage(page, queryWrapper);

        iPage.getRecords().stream().forEach(o -> {
            String roleName = "";
            try {
                o.setDeptName(SystemCache.deptMap.get(o.getDeptId()).getSimpleName());
                for (String roleId : Convert.toStrArray(o.getRoleId().split(","))) {
                    roleName += SystemCache.roleMap.get(roleId).getName() + " - ";
                }
            } catch (Exception e) {

            }
            o.setRoleName(roleName);
        });

        return LayuiPageFactory.listPage(iPage);
    }

    @Override
    public void setRoles(String id, String roleIds) {
        User user = new User();
        user.setId(id);
        user.setRoleId(roleIds);
        this.updateById(user);
    }

    @Override
    public void changePwd(String oldPassword, String newPassword) throws Exception{
        String userId = ShiroKit.getUserNotNull().getId();
        User user = this.getById(userId);

        String oldMd5 = ShiroKit.md5(oldPassword, user.getSalt());

        if (user.getPassword().equals(oldMd5)) {
            String newMd5 = ShiroKit.md5(newPassword, user.getSalt());
            user.setPassword(newMd5);
            this.updateById(user);
        } else {
            throw new Exception("原密码不正确");
        }
    }

}
